//
//  ScenesAudioUtils.cpp
//  ScenesPlayer
//
//  Created by Branch on 2016/11/2.
//  Copyright © 2016年 Scenes. All rights reserved.
//

#include "ScenesAudioUtils.h"
#include "utils/log.h"


namespace ScenesAudioUtils {
    const char SCENES_AUDIO_CODE[] = {22,16,36,(char)-85,(char)-52};
    
    
    const int kCheckSize = 20;     //从倒数第30的字节检查是否有森声的标志
    
    
    /**
     音频帧的最后五个字节存放识别标志码SCENES_AUDIO_CODE，倒数第六个字节存放音轨的个数。
     再往回每两个字节存放单个音轨的音频帧的大小。例如：
     有8条音轨，则倒数第六个字节的数值等于：8。
     倒数第八第七个字节存放一个int16_t型数据，数值为第八条音轨的音频帧的大小；

     @param buff buff description
     @param buffLen buffLen description
     @return return value description
     */
    std::vector<int> getAudioBuffInfo(uint8_t* buff, int buffLen,int* start){
        std::vector<int> ret;
        
        int codeLen = sizeof(SCENES_AUDIO_CODE) / sizeof(char);
        bool isScenes = false;
        for (int i = 0; i < kCheckSize; ++i) {
            if (buffLen <= codeLen) {
                //LOGE("is no scenes audio");
                return ret;
            }
            char* temp = (char*)buff + (buffLen - codeLen);
            bool t = true;
            for (int i = 0; i < codeLen; ++i) {
                if (SCENES_AUDIO_CODE[i] != *temp) {
                    t = false;
                    break;
                }
                ++temp;
            }
            if (t) {
                isScenes = true;
                break;
            }else{
                ++codeLen;
            }
           
        }
        
        if (!isScenes) {
            //LOGE("is no scenes audio");
            return ret;
        }
        
        
        
        int streamCount = *(buff + (buffLen - codeLen - 1));
        
        int16_t* infoStart = (int16_t*)(buff + (buffLen - codeLen - 1 - streamCount * sizeof(int16_t)));
        int s = 0;
        for (int i = 0; i < streamCount; ++i) {
            s += *infoStart;
            ret.push_back(*infoStart++);
        }
        int sta = buffLen - codeLen - 1 - streamCount * sizeof(int16_t) - s;
        if (sta >=0) {
            *start = sta;
        }

        //LOGV("getAudioBuffInfo streamCount:%d codeLen:%d s:%d buffLen:%d sta:%d",streamCount,codeLen,s,buffLen,sta);
        return ret;
    }
    
    bool isScenesAudio(uint8_t* buff, int buffLen){
        int start = 0;
        if (getAudioBuffInfo(buff,buffLen,&start).size() > 0) {
            return true;
        }
        return false;
    }
}
